﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MyAlbum.Logging;
using MyAlbum.Services;
using System.Data;
using System.Collections.Specialized;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
using System.Diagnostics;

namespace PersonalAlbum
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var iconfig = ObjectFactory.GetInstance<IConfiguration>();
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
            routes.IgnoreRoute("Resources/Images/*");
            routes.IgnoreRoute("Content/Images/*");
            routes.IgnoreRoute("HtmlEditor/editor/*");
            //url:http://localhost/sectionid/albumid/entryid
            //url:http://localhost/=> home page
            ///sectionid=>all albums for section
            ///sectionid/albumid=>all entries for album
            ///
            #region actions
            routes.MapRoute(
                "ShowUpdate",
                 (iconfig.UseAspxExtensions ? "{controller}.aspx/showUpdate/{id}" : "{controller}/showUpdate/{id}"),                           // URL with parameters
                    new { action = "showUpdate" }, // Parameter defaults
                     new {controller = @"[^\.]*", id = @"[\w\-]+" }
                );
            routes.MapRoute(
               "ShowCreate",
                (iconfig.UseAspxExtensions ? "{controller}.aspx/ShowCreate" : "{controller}/ShowCreate"),                           // URL with parameters
                   new { action = "ShowCreate" }, // Parameter defaults
                    new { controller = @"[^\.]*" }
               );

            routes.MapRoute(
               "Update",
                (iconfig.UseAspxExtensions ? "{controller}.aspx/Update/{id}" : "{controller}/Update/{id}"),                           // URL with parameters
                   new { action = "Update" }, // Parameter defaults
                    new { controller = @"[^\.]*", id = @"[\w\-]+" }
               );
            routes.MapRoute(
               "Create",
                (iconfig.UseAspxExtensions ? "{controller}.aspx/Create" : "{controller}/Create"),                           // URL with parameters
                   new { action = "Create" }, // Parameter defaults
                    new { controller = @"[^\.]*" }
               );

            #endregion

            #region albumsView
            if (iconfig.UseCategories)
            {
                //if we have categories, show albums per category
                routes.MapRoute(
                    "ShowAlbumsForSection",                                              // Route name
                    (iconfig.UseAspxExtensions ? "Category.aspx/{sectionId}/{page}" : "Category/{sectionId}/{page}"),                           // URL with parameters
                    new { controller = "Albums", action = "Index", page = "1", sectionId = "all" }, // Parameter defaults
                     new { page = @"^\d*$", sectionId = @"all|[\w\-]+" }
                );
            }
            else
            {
                //show the url as albums
                routes.MapRoute(
                                   "ShowAlbumsForSection",                                              // Route name
                                   (iconfig.UseAspxExtensions ? "Albums.aspx/{page}" : "Albums/{page}"),                           // URL with parameters
                                   new { controller = "Albums", action = "Index", sectionId = "all", page = "1" },  // Parameter defaults
                                    new { page = @"^\d*$", sectionId = @"all|[\w\-]+" }
                               );
            }
            #endregion

            //entries per album
            routes.MapRoute(
               "ShowEntriesForAlbum",                                              // Route name
               (iconfig.UseAspxExtensions ? "Album.aspx/{albumId}/{page}" : "Album/{albumId}/{page}"),                           // URL with parameters
               new { controller = "Entry", action = "Index", page = "1", albumId = "all" }, // Parameter defaults
                new { page = @"^\d*$", albumId = @"all|[\w\-]+" }
           );
          
            //all categories
            routes.MapRoute(
                     "Categories",                                              // Route name
                     (iconfig.UseAspxExtensions ? "Categories.aspx/{page}" : "Categories/{page}"),                           // URL with parameters
                     new { controller = "Categories", action = "Index", page = "1" }  // Parameter defaults
                     , new { page = @"^\d*$" }
                 );
            //routes.MapRoute(
            //                         "Albums",                                              // Route name
            //                         (iconfig.UseAspxExtensions ? "Albums.aspx/{sectionId}/{page}" : "Albums/{sectionId}/{page}"),                           // URL with parameters
            //                         new { controller = "Albums", action = "Index", page = "1", sectionId = "all" }  // Parameter defaults
            //                         ,null
            //                     );

            routes.MapRoute(
               "MetaWebLogAPI",
               (iconfig.UseAspxExtensions ? "MetaWebLogAPI.aspx/{request}" : "MetaWebLogAPI/{request}"),
               new { controller = "MetaWebLogAPI", action = "Index" });

            //if we have blog, it'll be the main page
            if (iconfig.ShowBlog)
            {
                if (iconfig.UseAspxExtensions)
                {
                    routes.MapRoute(
                         "Default.aspx",                                              // Route name
                         "default.aspx",                           // URL with parameters
                         new { controller = "MiniBlog", action = "Index", page = "1" }  // Parameter defaults
                         ,null
                     );
                }
                routes.MapRoute(
                      "Default",                                              // Route name
                      (iconfig.UseAspxExtensions ? "{controller}.aspx/{page}" : "{controller}/{page}"),                           // URL with parameters
                      new { controller = "MiniBlog", action = "Index", page = "1" }  // Parameter defaults
                      , new { page = @"^\d*$" }
                  );

            }
            else
            {
                if (iconfig.UseCategories)
                {
                    if (iconfig.UseAspxExtensions)
                    {
                        routes.MapRoute(
                             "Default.aspx",                                              // Route name
                             "default.aspx",                           // URL with parameters
                             new { controller = "Categories", action = "Index", page = "1" }  // Parameter defaults
                             , new { page = @"^\d*$" }
                         );
                    }
                    routes.MapRoute(
                      "Default",                                              // Route name
                      (iconfig.UseAspxExtensions ? "{controller}.aspx/{page}" : "{controller}/{page}"),                      // URL with parameters
                      new { controller = "Categories", action = "Index", page = "1" }  // Parameter defaults
                      , new { controller = @"[^\.]*", page = @"^\d*$" }
                  );
                }
                else
                {
                    if (iconfig.UseAspxExtensions)
                    {
                        routes.MapRoute(
                             "Default.aspx",                                              // Route name
                             "default.aspx",                           // URL with parameters
                             new { controller = "Albums", action = "Index", page = "1", sectionId = "all" }  // Parameter defaults
                             , new { page = @"^\d*$" }
                         );
                    }
                    routes.MapRoute(
                              "Default",                                              // Route name
                              (iconfig.UseAspxExtensions ? "{controller}.aspx/{page}" : "{controller}/{page}"),                          // URL with parameters
                               new { controller = "Albums", action = "Index", page = "1", sectionId = "all" }  // Parameter defaults
                              , new { controller = @"[^\.]*", page = @"^\d*$" }
                          );
                }
            }
            routes.MapRoute(
                     "All",                                              // Route name
                     (iconfig.UseAspxExtensions ? "{controller}.aspx/{action}/{id}" : "{controller}/{action}/{id}"),                           // URL with parameters
                     new { action = "Index",id="" }  // Parameter defaults
                     , null
                 );
            if (iconfig.UseAspxExtensions)
            {
                //default.aspx will not route otherwise, please note that you probably can't
                //use this option with existing web sites
                RouteTable.Routes.RouteExistingFiles = true;
            }
            else
            {
                //for existing webforms sites uncomment the following line:
                //routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            }


        }

        public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (string.Compare(custom, "lang", true) == 0)
            {
                return ObjectFactory.GetInstance<ILanguageService>().Language;
            }
            return base.GetVaryByCustomString(context, custom);
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            //try
            //{
            //    FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + @"\inetsrv\inetinfo.exe");
            //    Console.WriteLine("Version:" + fvi.FileVersion + "\nMajor Part: " + fvi.FileMajorPart + "." + fvi.FileMinorPart);
            //}
            //catch (FileNotFoundException ex)
            //{
            //    throw ex;
            //}
            //Response.Write("request");
            //try
            //{
            //    Response.Write(ObjectFactory.GetInstance<ILogger>().ToString());
            //    Response.Write(ObjectFactory.GetInstance<MyAlbum.Data.IEntryRepository>());
            //    Response.Write(ObjectFactory.GetInstance<MyAlbum.Data.IEntryRepository>().GetItems().ToList().Count);
            //}
            //catch (Exception e1)
            //{
            //    Response.Write(e1);
            //}
            // Response.End();
        }

        protected void Application_Error()
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                try
                {
                    HttpContext.Current.Response.Write(Server.GetLastError());
                    HttpContext.Current.Response.Flush();
                }
                catch (Exception e1)
                {
                    Response.Write("could not print error : " + e1.Message);
                }
            }
            else
            {
#endif
                try
                {
                    WebLogger.LogError(Server.GetLastError(), "Error on global");
                }
                catch
                {

                }
            }
           // Server.ClearError();
        }

        protected void Application_End()
        {
            WebLogger.Info("App is shutting down");
        }



        protected void Application_Start()
        {
            string result;
            if (!ConfigManager.Initalize(out result))
            {
                try
                {
                    Response.Write("<html><title>An error occurred</title><body>");
                    Response.Write(" Some errors occurred during initialization, please fix them:<br/>");
                    Response.Write(result);
                    Response.Write("</body></html>");
                    Response.End();
                }
                catch { }
            }
            RegisterModelBinders();
            RegisterRoutes(RouteTable.Routes);


              //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
#if StructureMap
            //     ControllerBuilder.Current.SetControllerFactory(
        //        new PersonalAlbum.Controllers.StructureMapControllerFactory()
          //      );

            Bootstrapper.ConfigureStructureMap();
#endif
#if Autofac
                   Bootstrapper.ConfigureAutoWiring();
#endif

            WebLogger.Trace("App is starting");
            ObjectFactory.GetInstance<ILanguageService>().SetDefaultLanaguage(ObjectFactory.GetInstance<IConfiguration>().DefaultLanguage);
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new ThemeViewEngine());
        }

        private void RegisterModelBinders()
        {
            ModelBinders.Binders[typeof(BlogML.Xml.BlogMLPost)] =
   new PostModelBinder();
        }
    }
}